<template>
  <div class="page-shopping-cart" id="shopping-cart">
    <h4 class="cart-title">购物清单</h4>
    <div class="cart-product clearfix">
      <table>
        <thead>
        <tr class="cart-product-title">
          <th class="td-check">
            <input type="checkbox" class="check-span fl check-all"  :class="{'check-true':isSelectAll}" @click="selectProduct(isSelectAll)" :checked="isSelectAll" id="checkAll"></input>全选</th>
          <th class="td-product">商品</th>
          <th class="td-num">数量</th>
          <th class="td-price">单价(元)</th>
          <th class="td-total">金额(元)</th>
          <th class="td-do">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item,index) in productList" :key="index">
          <td class="td-check"><input type="checkbox" class="check-span"  @click="item.select=!item.select" :class="{'check-true':item.select}" :checked="item.select"></input></td>
          <td class="td-product"><img :src="item.b_cover" width="98" height="98">
            <div class="product-info">
              <h3>{{item.b_name}}</h3>
              <p>作者：{{item.b_author}}</p>
              <p>出版社:{{item.b_publisher}}</p>
              <p>类型：{{item.bt_name}}</p>
              <p>出版时间：{{item.b_time}}</p>
            </div>
            <div class="clearfix"></div>
          </td>
          <td class="td-num">
            <div class="product-num">
              <a href="javascript:;" class="num-reduce num-do fl" @click="minus(index)"><span></span></a>
              <input type="text" class="num-input" v-model="item.num" @input="search($event,index)" @blur="check($event,index)">
              <a href="javascript:;" class="num-add num-do fr" @click="add(index)"><span></span></a>
            </div>
          </td>
          <td class="td-price">
            <p class="red-text">￥<span class="price-text">{{item.b_price.toFixed(2)}}</span></p>
          </td>
          <td class="td-total">
            <p class="red-text">￥<span class="total-text">{{(item.b_price*item.num).toFixed(2)}}</span></p>
          </td>
          <td class="td-do"><a href="javascript:;" class="product-delect"  @click="deleteOneProduct(item.sid)">删除</a></td>
        </tr>
        </tbody></table>
    </div>
    <div class="cart-product-info">
      <a class="delect-product" href="javascript:;" @click="deleteProduct">删除所选商品</a>
      <a class="keep-shopping" @click="touserhomepage">继续购物</a>
      <a class="btn-buy fr" href="javascript:;">去结算</a>
      <p class="fr product-total">￥<span>{{getTotal.totalPrice}}</span></p>
      <p class="fr check-num"><span>{{getTotal.totalNum}}</span>件商品总计（不含运费）：</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      productList: []
    }
  },
  computed: {
    isSelectAll:function(){
      //如果productList中每一条数据的select都为true，返回true，否则返回false;
      return this.productList.every(function (val) { return val.select});
    },
    getTotal:function(){
      //获取productList中select为true的数据。
      var _proList=this.productList.filter(function (val) { return val.select}),totalPrice=0;
      for(var i=0,len=_proList.length;i<len;i++){
        //总价累加
        totalPrice+=_proList[i].num*_proList[i].b_price;
      }
      //选择产品的件数就是_proList.length，总价就是totalPrice
      return {totalNum:_proList.length,totalPrice:totalPrice}
    }
  },
    mounted:function () {
      this.getShopCartList()
    },
  methods: {
    addSelect(){
      //为productList添加select（是否选中）字段，初始值为true
      var _this=this;
      //为productList添加select（是否选中）字段，初始值为true
      this.productList.map(function (item) {
        _this.$set(item, 'select', true);
      })
    },
    async getShopCartList() {
      try {
        const {data: res} = await this.$axios.get('/shopcart/getShopCartList', {params: {u_id: sessionStorage.getItem('u_id')}})
        this.productList = res.data
        this.addSelect()
        if (res.success) {
          this.productList = res.data
        } else {
          this.$message.error(res.message)
        }
      }catch (error) {
        console.error(error)
        this.$message.error('获取购物车列表失败')
      }
    },
    selectProduct:function(_isSelect){
      //遍历productList，全部取反
      for (var i = 0, len = this.productList.length; i < len; i++) {
        this.productList[i].select = !_isSelect;
      }
    },//删除已经选中(select=true)的产品
    deleteProduct:function () {
      this.productList=this.productList.filter(function (item) {return !item.select})
    },
    //删除单条产品
    deleteOneProduct:async function (sid) {
      //根据购物车记录sid删除购物车的记录
      const {data: res} = await this.$axios.get("/shopcart/deleteById", {params: {sid: sid}});
      if(res.data){
        this.$message.success("删除成功")
        await this.getShopCartList()
      }
    },
    search: function (event,index) {
      let flag = new RegExp("^[1-9]([0-9])*$").test(event.target.value);
      if(!flag){
        this.productList[index].num = '';
      }
    },
    check: function(event,index){
      if(event.target.value==''){
        this.productList[index].num = 0;
      }
    },
    //数量增加
    add: function(index){
      this.productList[index].num++;
    },
    //数量减少
    minus: function(index){
      if(this.productList[index].num>0){
        this.productList[index].num--;
      }else{
        this.productList[index].num = 0;
      }
    },
    touserhomepage(){
      this.$router.push('/userhome/homepage')
    }
  }
}
</script>

<style>
.clearfix:after {
  clear: both;
}
.page-shopping-cart {
  background-color: white;
  width: 1200px;
  margin: 5px auto;
  font-size: 14px;
  border: 1px solid #e3e3e3;
  border-top: 2px solid #317ee7; }
.page-shopping-cart .cart-title {
  color: #317ee7;
  font-size: 16px;
  text-align: center;
  padding-left: 20px;
  line-height: 68px; }
.page-shopping-cart .red-text {
  color: #e94826; }
.page-shopping-cart .check-span {
  display: block;
  width: 24px;
  height: 20px;}
.page-shopping-cart .td-check {
  width: 80px; }
.page-shopping-cart .td-product {
  width: 460px; }
.page-shopping-cart .td-num, .page-shopping-cart .td-price, .page-shopping-cart .td-total {
  width: 160px; }
.page-shopping-cart .td-do {
  width: 148px; }
.page-shopping-cart .cart-product-title {
  text-align: center;
  height: 38px;
  line-height: 38px;
  background: #f7f7f7; }
.page-shopping-cart .cart-product-title .td-product {
  text-align: center;
  font-size: 14px; }
.page-shopping-cart .cart-product-title .td-check {
  text-align: left; }
.page-shopping-cart .cart-product-title .td-check .check-span {
  margin: 9px 6px 0 0; }
.page-shopping-cart .cart-product {
  text-align: center; }
.page-shopping-cart .cart-product table {
  width: 100%;
  text-align: center;
  font-size: 14px; }
.page-shopping-cart .cart-product table th {
  padding: 10px;
}
.page-shopping-cart .cart-product table td {
  padding: 20px 10px; }
.page-shopping-cart .cart-product table tr {
  border-bottom: 1px dashed #e3e3e3; }
.page-shopping-cart .cart-product table tr:last-child {
  border-bottom: none; }
.page-shopping-cart .cart-product table .product-num {
  border: 1px solid #e3e3e3;
  display: inline-block;
  text-align: center; }
.page-shopping-cart .cart-product table .product-num .num-do {
  width: 24px;
  height: 28px;
  display: block;
  background: #f7f7f7; }
.page-shopping-cart .cart-product table .product-num .num-reduce span {
  background: url("@/assets/minus.png") no-repeat center;
  display: block;
  width: 24px;
  height: 28px;}
.page-shopping-cart .cart-product table .product-num .num-add span {
  background: url("@/assets/add.png") no-repeat center;
  display: block;
  width: 24px;
  height: 28px; }
.page-shopping-cart .cart-product table .product-num .num-input {
  width: 42px;
  height: 28px;
  line-height: 28px;
  border: none;
  text-align: center; }
.page-shopping-cart .cart-product table .td-product {
  text-align: left;
  font-size: 12px;
  line-height: 20px; }
.page-shopping-cart .cart-product table .td-product img {
  border: 1px solid #e3e3e3;
  margin-right: 10px; }
.page-shopping-cart .cart-product table .td-product .product-info {
  display: inline-block;
  vertical-align: middle; }
.page-shopping-cart .cart-product table .td-do {
  font-size: 12px; }
.page-shopping-cart .cart-product-info {
  height: 50px;
  line-height: 50px;
  background: #f7f7f7;
  padding-left: 20px; }
.page-shopping-cart .cart-product-info .delect-product {
  color: #666; }
.page-shopping-cart .cart-product-info .product-total {
  font-size: 14px;
  color: #e94826; }
.page-shopping-cart .cart-product-info .product-total span {
  font-size: 20px; }
.page-shopping-cart .cart-product-info .check-num {
  color: #333; }
.page-shopping-cart .cart-product-info .check-num span {
  color: #e94826; }
.page-shopping-cart .cart-product-info .keep-shopping {
  cursor: pointer; /* 设置鼠标悬停时为手型 */
  color: #666;
  margin-left: 40px; }
.page-shopping-cart .cart-product-info .btn-buy {
  height: 50px;
  color: #fff;
  font-size: 20px;
  display: block;
  width: 110px;
  background: #ff7700;
  text-align: center;
  margin-left: 30px; }
.page-shopping-cart .cart-worder {
  padding: 20px; }
.page-shopping-cart .cart-worder .choose-worder {
  color: #fff;
  display: block;
  background: #39e;
  width: 140px;
  height: 40px;
  line-height: 40px;
  border-radius: 4px;
  text-align: center;
  margin-right: 20px; }
.page-shopping-cart .cart-worder .worker-info {
  color: #666; }
.page-shopping-cart .cart-worder .worker-info img {
  border-radius: 100%;
  margin-right: 10px; }
.page-shopping-cart .cart-worder .worker-info span {
  color: #000; }
*{ box-sizing:border-box; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);}
*:focus { outline: none; }
html {  height: 100%;}
body { margin: 0;font-size:14px;line-height:1.5;  font-family:"微软雅黑",microsoft yahei; color:#333; background:#fff; }
body, div, span, object, iframe, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, q, dl, dt, dd, ol, ul, li, fieldset, form, legend, caption, tbody, tfoot, thead, article, aside, dialog, figure, footer, header, hgroup, nav, section{ padding:0; margin:0;}
audio, canvas, progress, video { display: inline-block; vertical-align: baseline; }
audio:not([controls]) { height: 0; }
[hidden], template {  display: none; }
a { color:#333;  background-color: transparent; text-decoration:none;  -webkit-touch-callout: none;}
a:active,a:hover {  outline: 0; }
img {  border: 0;vertical-align: middle; -webkit-touch-callout: none;}
h1,h2,h3,h4,h5,h6{ margin: 0;}
button, input, optgroup, select, textarea {  margin: 0;  font: inherit;  color: inherit; }
button { overflow: visible; }
[role='button']:focus{outline: 0;}
button,select {  text-transform: none; }
button,html input[type="button"],input[type="reset"],input[type="submit"] {  -webkit-appearance: button;  cursor: pointer; }
button[disabled], html input[disabled] {  cursor: default; }
button::-moz-focus-inner, input::-moz-focus-inner {  padding: 0;  border: 0; }
input {  line-height: normal; outline:none;}
input[type="checkbox"],input[type="radio"] {  -webkit-box-sizing: border-box;  -moz-box-sizing: border-box;  box-sizing: border-box;  padding: 0; }
input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button {  height: auto; }
input[type="search"] {  -webkit-box-sizing: content-box;     -moz-box-sizing: content-box;    box-sizing: content-box;  -webkit-appearance: textfield; }
input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration {  -webkit-appearance: none; }
input[type="text"]{-webkit-appearance: none;}
input[type="checkbox"]{ -webkit-appearance:checkbox;}
input[type="radio"]{ -webkit-appearance:radio;}
textarea {  overflow: auto; outline:none;-webkit-appearance: none;}
.clearfix:after{ content:""; display:block; clear:both; height:0; visibility:hidden;}
.clearfix{ zoom:1;}
.fl{float: left;}
.fr{float: right;}
</style>
